import { defineStore } from "pinia";

export const useLangStore = defineStore("lang", {
  state: () => ({
    currentLang: "pt", // 当前语言
    langs: {} as Record<string, any>, // 语言列表
  }),
  getters: {
    lang: (state) => {
      return (langName: string) => state.langs[langName] || undefined;
    },
  },
  actions: {
    async setLang() {
      try {
        // 获取所有语言文件
        const languageFiles = import.meta.glob(`~/assets/lang/**`, {
          eager: false,
        });
        const fileBase = `/assets/lang/${this.currentLang}/`;

        // 过滤并收集需要加载的文件
        const filesToLoad: Array<{
          name: string;
          importFn: () => Promise<any>;
        }> = [];

        for (const [filePath, importFn] of Object.entries(languageFiles)) {
          if (filePath.includes(fileBase)) {
            const name = filePath.split(fileBase)[1]?.replace(".ts", "");
            if (name) {
              filesToLoad.push({
                name,
                importFn: importFn as () => Promise<any>,
              });
            }
          }
        }

        if (filesToLoad.length === 0) {
          return this.langs;
        }

        // 并行加载所有文件
        const loadPromises = filesToLoad.map(async ({ name, importFn }) => {
          try {
            const module = await importFn();
            return { name, content: module.default || {} };
          } catch (error) {
            return { name, content: {} };
          }
        });

        // 等待所有文件加载完成
        const results = await Promise.all(loadPromises);

        // 使用 Object.fromEntries 替代 reduce，性能更好
        const newLangs = Object.fromEntries(
          results.map(({ name, content }) => [name, content])
        );

        // 一次性更新状态
        this.langs = { ...this.langs, ...newLangs };

        return this.langs;
      } catch (error) {
        return this.langs;
      }
    },
  },
});
